# frozen_string_literal: true

# == Schema Information
#
# Table name: vulnerabilities
#
#  id          :integer          not null, primary key
#  name        :string(255)      not null
#  scanner     :string(255)      default(""), not null
#  severity    :string(255)      default(""), not null
#  link        :string(255)      default(""), not null
#  fixed_by    :string(255)      default(""), not null
#  metadata    :text(65535)
#  description :text(65535)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#
# Indexes
#
#  index_vulnerabilities_on_name  (name) UNIQUE
#

# Vulnerability represents a vulnerability as detected by any of our sources.
class Vulnerability < ApplicationRecord
  has_many :scan_results, dependent: :destroy
  has_many :tags, -> { uniq }, through: :scan_results

  validates :name, uniqueness: true

  # Add some fields into this vulnerability object given an `obj` with the
  # `sc` scanner response.
  def add_extra_values!(obj:, sc:)
    attrs = fetch_attributes(obj: obj)
    attrs[:scanner] = sc if scanner.blank?
    update(attrs) unless attrs.empty?
  end

  # With the given objects, fetch the attributes to be updated for this object.
  def fetch_attributes(obj:)
    attrs = {}
    attrs[:fixed_by]    = obj["FixedBy"] if obj["FixedBy"].present?
    attrs[:link]        = obj["Link"] if obj["Link"].present?
    attrs[:metadata]    = obj["Metadata"] if obj["Metadata"].present?
    attrs[:severity]    = obj["Severity"] if obj["Severity"].present?
    attrs[:description] = obj["Description"] if obj["Description"].present?
    attrs
  end
end
